package com.kx.game.center.servlet;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kx.game.center.global.GSServices;
import com.kx.game.center.local.response.LocalErrorResponseCode;
import com.kx.game.center.redis.RedisConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 响应游戏服信息
 */
@WebServlet(urlPatterns = "/getServerInfos", asyncSupported = true)
public class GetServersServlet extends HttpServlet {

    private static Logger logger = LoggerFactory.getLogger(GetServersServlet.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            GSServices.loadManager.redisState();
            //游戏服信息
            List<JSONObject> jsonObjects = GSServices.redisManager.hashValues(RedisConstant.GAME_SERVER_LIST, JSONObject.class);
            JSONArray jsons = new JSONArray();
            for (JSONObject json : jsonObjects) {
//                if (json != null) {
//                    String serverId = json.getString("serverId");
//                    int gsLoginCount = GSServices.localManager.getGSLoginCount(serverId);
//                    json.put("loginNum", gsLoginCount);
//                }
                jsons.add(json);
            }
//            info.put("serverId", gameServerInfo.getString("serverId"));
//            info.put("ip", gameServerInfo.getString("ip"));
//            info.put("port", gameServerInfo.getString("port"));
//            info.put("state", gameServerInfo.getString("state"));
//            info.put("type", gameServerInfo.getString("type"));
//            String gateId = request.getParameter("gateId");
//            //网关信息
//            JSONObject gatewayInfo = GSServices.localManager.getGatewayInfo(gateId);
//            Integer gatewayLoad = GSServices.localManager.getGatewayLoad(gateId);
//            info.put("gateId", gateId);
//            info.put("gateIp", gatewayInfo.getString("Ip"));
//            info.put("gatePort", gatewayInfo.getString("port"));
//            info.put("gatewayLoad", gatewayLoad + "");
            GSServices.gameManager.printLog(request, logger, "GetServersInfo：发送数据" + jsons.toString());
            GSServices.localManager.sendMessage(response, true, null, jsons.toString());
        } catch (Exception e) {
            e.printStackTrace();
            GSServices.localManager.sendMessage(response, false, LocalErrorResponseCode.SYSTEM_ERROR, "");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
